package com.lixx.usercenter.services.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lixx.usercenter.common.ErrorCode;
import com.lixx.usercenter.contant.CommonConstant;
import com.lixx.usercenter.exception.BusinessException;
import com.lixx.usercenter.mapper.UserMapper;
import com.lixx.usercenter.model.domain.User;
import com.lixx.usercenter.model.domain.request.UserAddRequest;
import com.lixx.usercenter.model.domain.request.UserQueryRequest;
import com.lixx.usercenter.model.domain.request.UserUpdateRequest;
import com.lixx.usercenter.services.UserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

import static com.lixx.usercenter.contant.UserConstant.USER_LOGIN_STATE;

/**
 * @author KM
 * @description 针对表【user(用户表)】的数据库操作Service实现
 * @createDate 2025-07-29 23:53:47
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Autowired
    private UserMapper userMapper;

    /**
     * 盐
     */
    private static final String SALT = "lixx";


    /**
     * 用户注册
     *
     * @param userAccount   用户帐户
     * @param userPassword  用户密码
     * @param checkPassword 检查密码
     * @return long
     * @author Lixx
     * @date 2025/07/30
     */

    @Override
    public long userRegister(String userAccount, String userPassword, String checkPassword) {
        // 1. 校验
        if (StringUtils.isAnyBlank(userAccount, userPassword, checkPassword)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "参数为空");
        }
        // 账户长度不小于4位
        if (userAccount.length() < 4) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "账户长度不小于4位");
        }
        // 密码长度不小于8位
        if (userPassword.length() < 8 || checkPassword.length() < 8) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "密码长度不小于8位");
        }

        // 账户不包含特殊字符
        String validPattern = "[`~!@#$%^&*()+=|{}':;',\\\\[\\\\].<>/?~！@#￥%……&*（）——+|{}【】‘；：”“’。，、？]";
        Matcher matcher = Pattern.compile(validPattern).matcher(userAccount);
        if (matcher.find()) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "账户包含特殊字符");
        }

        // 密码和校验密码相同
        if (!userPassword.equals(checkPassword)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "密码和校验密码不相同");
        }
        // 账户不能重复
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userAccount", userAccount);
        Long count = userMapper.selectCount(queryWrapper);
        if (count > 0) {
            return -1;
        }

        // 2. 加密

        String encryptPassword = DigestUtils.md5DigestAsHex((SALT + userPassword).getBytes());
        // 3. 插入数据
        User user = new User();
        user.setUserAccount(userAccount);
        user.setUserPassword(encryptPassword);
        boolean result = this.save(user);
        if (!result) {
            return -1;
        }
        return 0;
    }

    /**
     * 用户登录
     *
     * @param userAccount  用户帐户
     * @param userPassword 用户密码
     * @return {@link User }
     * @author Lixx
     * @date 2025/07/30
     */

    @Override
    public User userLogin(String userAccount, String userPassword, HttpServletRequest request) {
        // 非空校验
        if (StringUtils.isAnyBlank(userAccount, userPassword)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "参数为空");
        }
        // 账户长度不小于4位
        if (userAccount.length() < 4) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "账户长度不小于4位");

        }
        // 密码长度不小于8位
        if (userPassword.length() < 8) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "密码长度不小于8位");
        }
        // 账户不包含特殊字符
        String validPattern = "[`~!@#$%^&*()+=|{}':;',\\\\[\\\\].<>/?~！@#￥%……&*（）——+|{}【】‘；：”“’。，、？]";
        Matcher matcher = Pattern.compile(validPattern).matcher(userAccount);
        if (matcher.find()) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "账户不包含特殊字符");
        }
        // 密码加密
        String encryptPassword = DigestUtils.md5DigestAsHex((SALT + userPassword).getBytes());

        // 查询用户
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userAccount", userAccount);
        queryWrapper.eq("userPassword", encryptPassword);
        User user = userMapper.selectOne(queryWrapper);
        if (user == null) {
            return null;
        }
        // 脱敏
        User safeUser = this.getSafeUser(user);
        // 登录态记录
        request.getSession().setAttribute(USER_LOGIN_STATE, safeUser);
        return safeUser;
    }

    /**
     * 用户注销
     *
     * @param request 请求
     * @return int
     * @author Lixx
     * @date 2025/07/30
     */

    @Override
    public int userLogout(HttpServletRequest request) {
        request.getSession().removeAttribute(USER_LOGIN_STATE);
        throw new BusinessException(ErrorCode.SUCCESS, "注销成功");
    }

    /**
     * 插入用户
     *
     * @param userAddRequest 用户添加请求
     * @return {@link Integer }
     * @author Lixx
     * @date 2025/08/05
     */

    @Override
    public Long insertUser(UserAddRequest userAddRequest, HttpServletRequest request) {
        // 参数校验
        if (StringUtils.isAnyBlank(userAddRequest.getUserAccount())){
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "参数为空");
        }
        // 账户长度不小于4位
        if (userAddRequest.getUserAccount().length() < 4){
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "账户长度小于4位");

        }
        // 账户不包含特殊字符
        String validPattern = "[`~!@#$%^&*()+=|{}':;',\\\\[\\\\].<>/?~！@#￥%……&*（）——+|{}【】‘；：”“’。，、？]";
        Matcher matcher = Pattern.compile(validPattern).matcher(userAddRequest.getUserAccount());
        if (matcher.find()) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "账户包含特殊字符");

        }
        // 账户不能重复
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userAccount", userAddRequest.getUserAccount());
        Long count = userMapper.selectCount(queryWrapper);
        if (count > 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "账户名重复");
        }
        // 设置默认密码
        String defaultPassword = "12345678";
        String encryptPassword = DigestUtils.md5DigestAsHex((SALT + defaultPassword).getBytes());
        User user = new User();
        // 复制属性
        BeanUtils.copyProperties(userAddRequest, user);
        user.setUserPassword(encryptPassword);
        int result = userMapper.insert(user);
        if (result <= 0) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "新增异常");
        }
        return user.getId();
    }

    /**
     * 删除用户
     *
     * @param id      id
     * @param request 请求
     * @return {@link Integer }
     * @author Lixx
     * @date 2025/08/05
     */

    @Override
    public Integer deleteUser(Long id, HttpServletRequest request) {
        if (id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "ID小于0");
        }
        int result = userMapper.deleteById(id);
        if (result <= 0) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "删除异常");
        }
        return result;
    }

    /**
     * 更新用户
     *
     * @param userUpdateRequest 用户更新请求
     * @param request           请求
     * @return {@link Integer }
     * @author Lixx
     * @date 2025/08/09
     */

    @Override
    public Integer updateUser(UserUpdateRequest userUpdateRequest, HttpServletRequest request) {
        // 密码长度不小于8位
        if (userUpdateRequest.getUserPassword().length() < 8) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "密码长度小于8位");
        }
        User user = new User();
        BeanUtils.copyProperties(userUpdateRequest, user);
        // 加密
        String encryptPassword = DigestUtils.md5DigestAsHex((SALT + userUpdateRequest.getUserPassword()).getBytes());
        user.setUserPassword(encryptPassword);
        int result = userMapper.updateById(user);
        if (result <= 0) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "更新异常");
        }
        return result;
    }

    /**
     * 列出用户
     *
     * @param userQueryRequest 用户查询请求
     * @return {@link Page }<{@link User }>
     * @author Lixx
     * @date 2025/08/07
     */

    @Override
    public Page<User> listUser(UserQueryRequest userQueryRequest) {
        if (userQueryRequest == null) {
            return null;
        }
        // 获取分页参数
        long current = userQueryRequest.getCurrent();
        long size = userQueryRequest.getPageSize();
        // TODO：安全校验-考虑安全性

        Page<User> userPage = userMapper.selectPage(new Page<>(current, size), this.getQueryWrapper(userQueryRequest));
        // 1. 获取分页查询数据集合，并通过stream()方法获取集合对象
        List<User> safetyUserList = userPage.getRecords().stream()
                // 2. 使用map()方法用于执行需要的处理逻辑
                .map(this::getSafeUser)
                // 3. 使用collect()方法将处理后的数据收集到一个新的列表中
                .collect(Collectors.toList());
        // 4. 将处理后的数据集合赋给userPage对象
        userPage.setRecords(safetyUserList);
        return userPage;
    }

    /**
     * 获取安全用户
     *
     * @param originUser 源用户
     * @return {@link User }
     * @author Lixx
     * @date 2025/08/07
     */

    @Override
    public User getSafeUser(User originUser) {
        if (originUser == null) {
            return null;
        }
        User safetyUser = new User();
        safetyUser.setId(originUser.getId());
        safetyUser.setUsername(originUser.getUsername());
        safetyUser.setUserAccount(originUser.getUserAccount());
        safetyUser.setAvatarUrl(originUser.getAvatarUrl());
        safetyUser.setGender(originUser.getGender());
        safetyUser.setPhone(originUser.getPhone());
        safetyUser.setEmail(originUser.getEmail());
        safetyUser.setUserRole(originUser.getUserRole());
        safetyUser.setCreateTime(originUser.getCreateTime());
        safetyUser.setUpdateTime(originUser.getUpdateTime());
        return safetyUser;
    }

    /**
     * 获取查询包装器
     *
     * @param userQueryRequest 用户查询请求
     * @return {@link QueryWrapper }<{@link User }>
     * @author Lixx
     * @date 2025/08/07
     */

    @Override
    public QueryWrapper<User> getQueryWrapper(UserQueryRequest userQueryRequest) {
        if (userQueryRequest == null) {
            return null;
        }
        Long id = userQueryRequest.getId();
        String username = userQueryRequest.getUsername();
        String userAccount = userQueryRequest.getUserAccount();
        Integer gender = userQueryRequest.getGender();
        Integer userStatus = userQueryRequest.getUserStatus();
        Integer userRole = userQueryRequest.getUserRole();
        Date createTime = userQueryRequest.getCreateTime();
        String sortField = userQueryRequest.getSortField();
        String sortOrder = userQueryRequest.getSortOrder();
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(id != null, "id", id);
        queryWrapper.like(StringUtils.isNotBlank(username), "username", username);
        queryWrapper.like(StringUtils.isNotBlank(userAccount), "userAccount", userAccount);
        queryWrapper.eq(gender != null, "gender", gender);
        queryWrapper.eq(userStatus != null, "userStatus", userStatus);
        queryWrapper.eq(userRole != null, "userRole", userRole);
        queryWrapper.eq(createTime != null, "createTime", createTime);
        queryWrapper.orderBy(StringUtils.isNotBlank(sortField),
                sortOrder.equals(CommonConstant.SORT_ORDER_ASC), sortField);
        return queryWrapper;
    }
}




